<template>
    <div>
      <div>
        <button class="" @click="createMeasureDiatance()">画图测距</button>
        <button class="" @click="draw()">绘制</button>
        <button class="" @click="disDraw()">关闭绘制</button>
        <button @click="create()">绘制矩形</button>
        <button @click="createIcon()">画icon</button>
        <button @click="removeIcon()">移除icon</button>
        <button @click="createAnno()">画注记</button>
        <button @click="removeAnno()">移除注记</button>
        <button @click="createPoint()">画点</button>
        <button @click="removePoint()">移除点</button>
        <button @click="createLine()">画线</button>
        <button @click="removeLine()">移除线</button>
        <button @click="createPolygon()">绘制多变形</button>
        <button @click="removePolygon()">移除多变形</button>
        <button @click="createpopup()">绘制弹出框</button>
        <button @click="createFlicker()">实现闪动效果</button>
        <button @click="addGatheringPlace()">腰子</button>
        <button @click="addStraightArrow()">直箭头</button>
        <button @click="addFineArrow()">细直箭头</button>
        <button @click="addAssaultDirection()">突击方向</button>
        <button @click="addAttackArrow()">进攻方向</button>
        <button @click="addTailedAttackArrow()">进攻方向（尾）</button>
        <button @click="addSquadCombat()">分队战斗行动</button>
        <button @click="addTailedSquadCombat()">分队战斗行动（尾）</button>
        <button @click="getLoc()">获取位置信息</button>
        <button @click="drag()">拖拽</button>


  	<button @click="drawRectangle">绘制预测区域</button>
  	<button @click="editDrawRectangle">编辑已绘区域</button>
  	<button @click="dragDrawRectangle">拖拽移动</button>
  	<button @click="deleteDrawRectangle">删除区域</button>


      <!-- <a-icon type="edit" @click="blindClick" class="draw" /> -->
      <!-- <button  @click="cancleDraw" class="cancle" >取消</button> -->
    </div>
      <div id="map"></div>
    </div>
</template>

<script>
// 基础功能的实现

// 计算工具
import "../../../public/static/leaflet/PlotUtil.min.js";
// 标绘图形
import "../../../public/static/leaflet/Plots.min.js";

var DRAWING = false; //是否正在绘制
var DRAWLAYERS = [];
var BarDRAWLAYERS = [];

var MEASURETOOLTIP; //量距提示
var MEASURERESULT = 0; //测量结果

var DRAWPOLYLINE; //绘制的折线
var DRAWMOVEPOLYLINE; //绘制过程中的折线
var DRAWPOLYLINEPOINTS = []; //绘制的折线的节点集
var shapeOptions = {
  color: '#F54124',
  weight: 3,
  opacity: 0.8,
  fill: false,
  clickable: true
};

let map = null;
export default {
  data() {
    return {
      drawType:true,
      map: "",
      list: [], //存放矩形点数据
      rectgroup: "", //矩形图层
      cirgroup: "", //点图层
      markerlist: [], //点名称
      testgroup: "", //移动时绘制矩形图形的图层
      pointMarkerList: [], // 保存点位的数组变量
      lineList: [], // 线的变量
      polygonList: [], // // 存储画的多边形
      iconList: [],
      annoList: [],
      regionList: [], // 腰子
      lat: '',
      // 经度
      lng: '',
      latlngArr: [],
      polygonArr: [],
      rectangleGeoJson: {},
      rectangleLayer: {},
    };
  },
  mounted() {
    // let _this = this
    this.loadMap();
  },
  methods: {
    drawRectangle() {
      // 删除已有图形
      this.deleteDrawRectangle()
      // 激活绘制多边形功能
      this.rectangleLayer = this.map.pm.enableDraw('Polygon', {
        snappable: true,
        snapDistance: 20,
        allowSelfIntersection: false
      });
    },
    editDrawRectangle() {
      this.map.pm.toggleGlobalEditMode()
      // 监听编辑
      this.rectangleLayer.on('pm:edit', function (e) {
        // 记录当前绘制的图形
        this.rectangleGeoJson = e.target.toGeoJSON();
        this.rectangleLayer = e.layer;
      })

    },
    dragDrawRectangle() {
      this.map.pm.toggleGlobalDragMode()
      this.rectangleLayer.on("pm:drag", e => {
        console.log(e, "开始拖动");
      });
      // 监听拖拽
      this.rectangleLayer.on('pm:dragend', function (e) {
        this.rectangleGeoJson = e.target.toGeoJSON();
        this.rectangleLayer = e.layer;
      })

    },
    deleteDrawRectangle() {
      console.log(this.rectangleLayer)
      // this.map.removeLayer(this.rectangleLayer)
    },
    drag(){
      let that = this;
      this.map.pm.toggleGlobalDragMode();
      this.map.on("pm:create", e => {
        console.log(e, that.map.pm.Draw.getShapes(),"创建结束");
      });
    },
    getLoc() {
      this.iconList.forEach(item => {
        console.log("icon", "[" + item._latlng.lat, item._latlng.lng + "]");
      });
      // this.pointMarkerList.forEach(item => {
      //   console.log(item)
      // })
      // this.lineList.forEach(item => {
      //   console.log(item)
      // })
      // this.polygonList.forEach(item => {
      //   console.log(item)
      // })
    },
    loadMap() {
      map = L.map("map");
      L.tileLayer(
        // 谷歌卫星瓦片
        // "https://gac-geo.googlecnapps.cn/maps/vt?lyrs=s,m&gl=CN&x={x}&y={y}&z={z}",
        // "http://mt2.google.cn/vt/lyrs=m&scale=2&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}",
        // "https://mt1.google.com/vt/lyrs=t&x={x}&y={y}&z={z}",
        // "http://t7.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=e3b434f191257368fc43c5b011ab5911",
        "http://api0.map.bdimg.com/customimage/tile?&x={x}&y={y}&z={z}",
        {
          maxZoom: 18,
          minZoom: 7,
          // attribution: "谷歌地图",
          // subdomains: ["1", "2", "3", "4"],
          center: [40.35,117.36],
          zoom: 6,
          zoomControl: true, //禁用 + - 按钮
          doubleClickZoom: true, // 禁用双击放大
          attributionControl: true, // 移除右下角leaflet标识
          dragging: true, //禁止鼠标拖动滚动
          boxZoom: true, //决定地图是否可被缩放到鼠标拖拽出的矩形的视图，鼠标拖拽时需要同时按住shift键.
          scrollWheelZoom: true //禁止鼠标滚动缩放
        }
      ).addTo(map);
        map.setView([40.35,117.36],7)

      // 绑定点击事件获取属性信息
      // map.on("click", e => {
      //   console.log("点击了", e);
      //   // 经度 e.latlng.lat
      //   // 维度 e.latlng.lng
      //   let data = e.target.options.data; //marker的属性信息
      // });
      map.off('click')    // 关闭单击事件
      map.off('dblclick') // 关闭双击事件
      map.off('mousemove') // 关闭鼠标移动事件
      this.map = map;
      this.plotLayer = L.featureGroup().addTo(map);
      // 配置绘画工具
      this.map.pm.addControls({
        position: "topleft",
        drawPolygon: false, // 添加绘制多边形
        drawMarker: false, //添加按钮以绘制标记
        drawCircleMarker: false, //添加按钮以绘制圆形标记
        drawPolyline: false, //添加按钮绘制线条
        drawRectangle: false, //添加按钮绘制矩形
        drawCircle: false, //  添加按钮绘制圆圈
        editMode: false, //  添加按钮编辑多边形
        dragMode: false, //   添加按钮拖动多边形
        cutPolygon: false, // 添加一个按钮以删除图层里面的部分内容
        removalMode: false // 清除图层
      });
      // 设置绘制后的线条颜色等
      this.map.pm.setPathOptions({
        color: "pink",
        fillColor: "#FF0000",
        fillOpacity: 0.4
      });
      this.map.pm.setLang("zh"); //设置语言  en, de, it, ru, ro, es, fr, pt_br, zh , nl
      this.drawPoint();
      this.rectgroup = L.featureGroup([]); //创建图层
      this.map.addLayer(this.rectgroup);
      this.cirgroup = L.featureGroup([]); //创建图层
      this.map.addLayer(this.cirgroup);
      this.testgroup = L.featureGroup([]); //创建图层
      this.map.addLayer(this.testgroup);
           // 监听创建图形
      this.map.on('pm:create', (e) => {
        // 记录当前绘制的图形
        this.rectangleGeoJson = e.layer.toGeoJSON()
        this.rectangleLayer = e.layer
      });
    },
       // 绘制地理位置
    drawPoint() {
      if (marker) {
        // 移除 marker
        map.removeLayer(marker)
        // marker.setLatLng([this.lat, this.lng])
      }
      marker = L.marker([this.lat, this.lng], { icon: comIcon })
      marker.bindPopup('点位置')
      map.addLayer(marker)
    },
    // 实现闪动效果
    createFlicker() {
      let disLayer = L.rectangle(
        [[40.35, 117.36], [36.35, 114.36], [37.35, 114.36], [36.35, 119.36]],
        {
          color: "red"
        }
      ).addTo(map);
      console.log("disLayer", disLayer);
      /**开始闪烁*/
      //flag为ture时，图形消失；反之，图形显现
      var flag = true;
      //开启计时器
      let id = setInterval(function() {
        if (flag) {
          //移除图形
          map.removeLayer(disLayer);
          flag = false;
        } else {
          //添加图形
          map.addLayer(disLayer);
          flag = true;
        }
      }, 500);
    },
    createAnno() {
      // 绘制注记
      let markerIcon = L.divIcon({
        html: "我是标注", //marker标注
        className: "my-div-icon",
        iconSize: [57, 71], //marker宽高
        iconAnchor: [28.5, 55], //文字标注相对位置
        color: "#FF0000"
      });
      // 1.添加注记
      var markers = [
        [40.35, 117.36],
        [36.35, 114.36],
        [42.12, 113.933657],
        [36.151044, 120.510406],
        [36.195387, 120.605164],
        [36.261854, 120.559845]
      ];
      for (var i = 0; i < markers.length; i++) {
        const anno = L.marker(markers[i], { icon: markerIcon }).addTo(map);
        this.annoList.push(anno);
      }
    },
    removeAnno() {
      this.annoList.forEach(item => {
        this.map.removeLayer(item);
      });
      this.annoList = [];
    },
    // 绘制单个icon
    createIcon() {
      const icon = L.marker([39.96, 1116.39], {
        icon: new L.Icon({
          className: "lmap-icon",
          iconUrl: require("./../../assets/avatar.png"),
          iconSize: [24, 24],
          iconAnchor: [16, 16]
        }),
        draggable: true
      }).addTo(map);
      const that = this;
      //拖拽结束
      icon.on("dragend", function(e) {
        console.log(icon);
        const pos = icon.getLatLng();
        console.log(pos);
        const posy = pos.lat;
        const posx = pos.lng;
        console.log("实时坐标：" + icon.getLatLng());
        that.removeIcon();
        const icon1 = L.marker([posy, posx], {
          icon: new L.Icon({
            className: "lmap-icon",
            iconUrl: require("./../../assets/avatar.png"),
            iconSize: [24, 24],
            iconAnchor: [16, 16]
          }),
          draggable: true
        }).addTo(map);

        that.iconList.push(icon1);
        console.log(that.iconList);
      });

      this.iconList.push(icon);

      //  marker 移动
      var pos = map.latLngToLayerPoint(icon.getLatLng());
      var fx = new L.PosAnimation();
      fx.run(icon._icon, pos, 0.3);
      let x = 116.39;
      let y = 39.96;
      fx.on("end", () => {
        icon.setLatLng(L.latLng(y, x));
        x += 0.002;
        y += 0.002;
        let pos = map.latLngToLayerPoint({ lng: x, lat: y });
        fx.run(icon._icon, pos, 1, (0, 0, 1, 1));
      });
    },
    removeIcon() {
      this.iconList.forEach(item => {
        this.map.removeLayer(item);
      });
      this.iconList = [];
    },
    createPoint() {
      // 绘制点或者圆
      const marker = L.circle([40.35, 117.36], {
        color: "#FF0000", //边框颜色
        fillColor: "transparent", //内部填充颜色
        radius: 80000,
        fillOpacity: 0.8
      }).addTo(map);
      this.pointMarkerList.push(marker);
    },
    // 点位的删除
    removePoint() {
      this.pointMarkerList.forEach(item => {
        this.map.removeLayer(item);
      });
      this.pointMarkerList = [];
    },
    createLine() {
      // 绘制线条
      // var latlngs =[[51.505,-0.09],[52,-1],[51,-0.05]]
      var latlngs = [[40.35, 117.36], [36.35, 114.36], [42.12, 113.933657]];
      var polyline = L.polyline(latlngs, { color: "red" }).addTo(map);
      this.lineList.push(polyline);
    },
    removeLine() {
      this.lineList.forEach(item => {
        this.map.removeLayer(item);
      });
      this.lineList = [];
    },
    // 绘制多边形
    createPolygon() {
      var latlngs = [[40.35, 117.36], [36.35, 114.36], [42.12, 113.933657]];
      var polygon = L.polygon(latlngs, {
        color: "#000eff",
        fillColor: "#0000ed",
        weight: 1
      }).addTo(map);

      polygon.bindPopup("我是个多边形");

      this.polygonList.push(polygon);
    },
    // 面的删除
    removePolygon() {
      this.polygonList.forEach(item => {
        this.map.removeLayer(item);
      });
      this.polygonList = [];
    },
    // 绘制弹窗
    createpopup() {
      var popup = L.popup()
        .setLatLng([40.35, 117.36])
        .setContent("<p>你好呀！<br />我是个弹窗框.</p>")
        .openOn(map);
      // 或着对绘制好的图形绑定弹出框，在点击这个图形后会弹出你想要你内容
    },
    addGatheringPlace() {
      // 腰子
      const that = this;
      // L.Plot.gatheringPlace([
      //   [36.151044, 120.510406],
      //   [36.195387, 120.605164],
      //   [36.261854, 120.559845]
      // ])
      const region = L.Plot.gatheringPlace(
        // [[40.35, 117.36], [36.35, 114.36], [42.12, 113.933657]],
        [
          [36.151044, 120.510406],
          [36.195387, 120.605164],
          [36.261854, 120.559845]
        ],
        { draggable: true }
      ).addTo(map);
      const icon = L.marker([39.96, 1116.39], {
        icon: new L.Icon({
          className: "lmap-icon",
          iconUrl: require("./../../assets/avatar.png"),
          iconSize: [24, 24],
          iconAnchor: [16, 16]
        }),
        draggable: true
      }).addTo(map);
      //拖拽结束
      region.on("dragend", function(e) {
        that.removeRegion();
        console.log(region);
        const pos = region.getLatLng();
        console.log(pos);
        const posy = pos.lat;
        const posx = pos.lng;
        console.log("实时坐标：" + region.getLatLng());

        that.regionList.push(region1);
        //  console.log(that.iconList)
      });
      that.regionList.push(icon);
    },
    editMapLayer(layer) {
      layer.pm.enable({
        allowSelfIntersection: true,
        preventMarkerRemoval: false // 禁止右键删除点
      });
      let that = this;
      // 监听编辑事件
      layer.on("pm:edit", e => {
        // 拖动后的坐标
        that.currentGridData.rangePoints = e.target._latlngs[0];
      });
      layer.on("pm:vertexadded", e => {
        // 添加顶点
        console.log(e, "添加顶点");
      });
    },
    removeRegion() {
      this.regionList.forEach(item => {
        this.map.removeLayer(item);
      });
      this.regionList = [];
    },
    draw() {
      this.measureDis()
      // return
      // this.map.pm.enableDraw("Polygon", {
      //   snappable: false
      // });
      //设置地图的鼠标按下事件
      //   this.map.pm.enableDraw("Marker", { snappable: false });
      //   this.map.pm.enableDraw("CircleMarker", { snappable: false });
      // this.measureDis()
    },
    createMeasureDiatance(){ // 距离
      map.getContainer().style.cursor = 'crosshair';

      //绘制的折线
      DRAWPOLYLINE = new L.Polyline([], shapeOptions);
      //地图上添加折线
      map.addLayer(DRAWPOLYLINE);
      //实例化量距提示
      MEASURETOOLTIP = new L.Tooltip(map);
      //设置地图的鼠标按下事件
      map.on('mousedown', this.onClick);
      //设置地图的双击事件
      map.on('dblclick', this.onDoubleClick);
    },
    measureDis(){ // 测量距离
      // 41.40657708472196,112.64319881126578
      var arr = [{ lat: 41.43147131637866, lng: 112.29152775756754 }, { lat: 41.34896464345427, lng: 113.29159231652191 }];
      // 示例用法
      const distance = this.calculateDistance(41.17524004258887,  112.86299321982717, 41.11727764148575,  113.30258203694999);
      console.log("37.37公里",distance); // 输出两点之间的距离（单位：千米）
      //地图上添加标记
      const icon = L.marker({ lat: 41.34896464345427, lng: 113.29159231652191 }, {
        icon: new L.Icon({
          className: "lmap-icon",
          iconUrl: require("./../../assets/avatar.png"),
          iconSize: [24, 24],
          iconAnchor: [16, 16]
        }),
        draggable: true
      }).addTo(map);

      //标记绑定弹窗显示
      icon.bindPopup((distance).toFixed(2) + "公里").openPopup();
    },
     calculateDistance(lat1, lon1, lat2, lon2) {
      //通过Haversine公式来计算两个经纬度坐标之间的距离。
      //这段代码接受四个参数，分别是第一个点的纬度（lat1）、经度（lon1），以及第二个点的纬度（lat2）、经度（lon2）。函数将返回两点之间的距离，单位为千米。
      const R = 6371; // 地球半径（单位：千米）
      const dLat = (lat2 - lat1) * (Math.PI / 180);
      const dLon = (lon2 - lon1) * (Math.PI / 180);
      const a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(lat1 * (Math.PI / 180)) *
        Math.cos(lat2 * (Math.PI / 180)) *
        Math.sin(dLon / 2) *
        Math.sin(dLon / 2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      const distance = R * c;
      return distance;
    },
    //鼠标按下事件
    onClick(e) {
      console.log("是否绘制",e.latlng)
      DRAWING = true; //是否正在绘制
      DRAWPOLYLINEPOINTS.push(e.latlng); //绘制的折线的节点集
      //测量结果加上距离上个点的距离
      MEASURERESULT += e.latlng.distanceTo(DRAWPOLYLINEPOINTS[DRAWPOLYLINEPOINTS.length-2]);
      console.log(DRAWPOLYLINEPOINTS[DRAWPOLYLINEPOINTS.length - 1])
      //绘制的折线添加进集合
      DRAWPOLYLINE.addLatLng(e.latlng);
      //地图添加鼠标移动事件
      map.on('mousemove', this.onMove);
    },
    //鼠标移动事件
    onMove(e) {
      if (DRAWING) { //是否正在绘制
        //将上次的移除
        if (DRAWMOVEPOLYLINE != undefined && DRAWMOVEPOLYLINE != null) { //绘制过程中的折线
          map.removeLayer(DRAWMOVEPOLYLINE);
        }
        //获取上个点坐标
        var prevPoint = DRAWPOLYLINEPOINTS[DRAWPOLYLINEPOINTS.length - 1];
        //绘制最后一次的折线
        DRAWMOVEPOLYLINE = new L.Polyline([prevPoint, e.latlng], shapeOptions);
        //添加到地图
        map.addLayer(DRAWMOVEPOLYLINE);
        //累加距离
        var distance = MEASURERESULT + e.latlng.distanceTo(DRAWPOLYLINEPOINTS[DRAWPOLYLINEPOINTS
          .length - 1]);
      }
    },
    //鼠标双击事件
    onDoubleClick(e) {
      map.getContainer().style.cursor = '';
      /*显示两点距离*/
      //之前的距离加上最后一次的距离
      var distance = MEASURERESULT + e.latlng.distanceTo(DRAWPOLYLINEPOINTS[DRAWPOLYLINEPOINTS.length -
        1]);
        console.log("distance", distance)
      const icon = L.marker(e.latlng, {
        icon: new L.Icon({
          className: "lmap-icon",
          iconUrl: require("./../../assets/avatar.png"),
          iconSize: [24, 24],
          iconAnchor: [16, 16]
        }),
        draggable: true
      }).addTo(map);
      //地图上添加标记
      // map.addLayer(marker);
      //标记绑定弹窗显示
      icon.bindPopup((distance / 1000).toFixed(2) + "公里").openPopup();
      if (DRAWING) {
        //清除上次的
        if (DRAWMOVEPOLYLINE != undefined && DRAWMOVEPOLYLINE != null) {
          map.removeLayer(DRAWMOVEPOLYLINE);
          DRAWMOVEPOLYLINE = null;
        }
        BarDRAWLAYERS.push(DRAWPOLYLINE);
        DRAWPOLYLINEPOINTS = [];
        DRAWING = false;
        //移除事件
        map.off('mousedown');
        map.off('mousemove');
        map.off('dblclick');
      }
    },
    disDraw() {
      this.map.pm.disableDraw("Polygon");
      this.map.pm.disableDraw("Marker");
      this.map.pm.disableDraw("CircleMarker");
    },
    getlatLngs() {
      //pm:drawstart 开始第一个点的时候调用
      //pm:drawend  禁止绘制时调用
      //pm:create  创建完成时调用
      this.map.on("pm:drawstart", e => {
        console.log(e, "first");
      });
      this.map.on("pm:drawend", e => {
        console.log(e, "禁止绘制");
      });
      this.map.on("pm:create", e => {
        console.log(e, "绘制完成时调用");
        console.log(e.layer._latlngs[0], "绘制坐标");
      });
    },
    //  绘制
    drawPoint() {
      L.circle([51.3, -0.06], {
        color: "#FF0000",
        fillColor: "#FF0000",
        radius: 1000,
        fillOpacity: 1
      }).addTo(map);
    },
    drawLine() {
      var latlngs = [[51.505, -0.09], [52, -1], [51, -0.05]];
      var polyline = L.polyline(latlngs, { color: "red" }).addTo(map);
      var popup = L.popup()
        .setLatLng([51.505, -0.19])
        .setContent("<p>Hello world!<br />This is a nice popup.</p>")
        .openOn(map);

      polygon.bindPopup("我是个xian");
    },
    drawPolygon() {
      var latlngs = [[51.505, -0.09], [52, -1], [51, -0.05], [51.3, -0.06]];
      var polygon = L.polygon(latlngs, {
        color: "#000eff",
        fillColor: "#0000ed",
        weight: 1
      }).addTo(map);
      //  var popup = L.popup()
      //       .setLatLng([51.505, -0.19])
      //       .setContent('<p>Hello world!<br />This is a nice popup.</p>')
      //       .openOn(map);

      // polygon.bindPopup("我是个多边形")
    },
    // 进攻方向
    addAttackArrow() {
      L.Plot.attackArrow([
        [36.146608, 119.994049],
        [36.145499, 120.017395],
        [36.288425, 119.996796]
      ]).addTo(map);
    },
    // 画矩形
    create() {
      let list = [];
      let juxing;
      this.map.on("click", e => {
        list.push([e.latlng.lat, e.latlng.lng]);
        this.map.on("mousemove", ev => {
          if (list.length > 1) {
            list.splice(1);
          }
          list.push([ev.latlng.lat, ev.latlng.lng]);
          this.testgroup.clearLayers();
          juxing = L.rectangle(list, {
            //绘制矩形
            color: "#ff7800",
            weight: 1
          }).addTo(this.testgroup);

          juxing.once('mousedown', function (e) {
            //获取鼠标按下位置的纬经度坐标
            var coordinate1 = e.latlng;
            //监听地图移动事件，实时改变图形位置
            map.on('mousemove ', function (e) {
              //移动位置处的坐标
              var coordinate2 = e.latlng;
              //计算坐标偏移
              var dx = coordinate2.lat - coordinate1.lat;
              var dy = coordinate2.lng - coordinate1.lng;
              //重新设置矩形位置
              var latlngs = [[36.09 + dx, 120.35 + dy], [36.12 + dx, 120.55 + dy]];
              rectangle.setBounds(latlngs);
            });
          });

          /**矢量图层鼠标释放事件
          *  @param {string} type 事件类型（鼠标释放）
          *  @param {function} fn 事件触发后的响应函数
          */
          juxing.once('mouseup', function (e) {
            //鼠标释放后，注销鼠标移动事件
            map.off('mousemove');
            alert("移动完成！");
          });


        });
        if (list.length > 1) {
          list.pop(); //第二次点击会触发第一次的push（）导致得到三个数据（后两个一样），所以删除最后一个
          // this.list.push([list])//保存矩形数据
          this.list.push({
            first: list[0],
            sec: list[1],
            name: "矩形" + (this.list.length + 1)
          }); //保存矩形数据
          this.map.off("mousemove"); //两点确定，移除鼠标移动事件
          this.map.off("click"); //两点确定，移除点击事件，
          this.testgroup.clearLayers();
          L.rectangle(list, {
            //绘制矩形
            color: "#ff7800",
            weight: 1
          }).addTo(this.rectgroup);
        }
      });
    },
    change(data) {
      this.markerlist = [];
      for (let key in data) {
        if (key !== "name") {
          let marker = "marker" + key;
          marker = L.marker(new L.LatLng(data[key][0], data[key][1]), {
            // 创建点
            icon: this.shipWreckIcon,
            draggable: true
          }).addTo(this.cirgroup);
          let _this = this;
          marker.on("drag", function(e) {
            data[key] = [e.latlng.lat, e.latlng.lng];
            _this.drawrect(_this.rectgroup, [data]);
          });
          this.markerlist.push(marker);
        }
      }
    },
    drawrect(group, data, clear = true) {
      data.forEach((items, index) => {
        let list = [items.first, items.sec];
        if (clear) {
          group.clearLayers(); //清除当前绘制的图层，保留了原有图层，需要删除可以添加
        }
        L.rectangle(list, {
          //绘制矩形
          color: "#ff7800",
          weight: 1
        }).addTo(group);
      });
    },
    sub() {
      this.markerlist.forEach(item => {
        item.off("drag");
      });
      this.cirgroup.clearLayers();
      this.testgroup.clearLayers();
      this.rectgroup.clearLayers();
      this.drawrect(this.rectgroup, this.list, false);
    },
    // 直箭头
    addStraightArrow() {
      L.Plot.straightArrow([
        [36.145499, 119.838867],
        [36.295066, 119.8526]
      ]).addTo(this.plotLayer);
    },
    // 细直箭头
    addFineArrow() {
      L.Plot.fineArrow([
        [36.280676, 119.903412],
        [36.143281, 119.895172]
      ]).addTo(this.plotLayer);
    },
    // 突击方向
    addAssaultDirection() {
      L.Plot.assaultDirection([
        [36.142172, 119.941864],
        [36.276248, 119.962463]
      ]).addTo(this.plotLayer);
    },
    // 进攻方向
    addAttackArrow() {
      L.Plot.attackArrow([
        [36.146608, 119.994049],
        [36.145499, 120.017395],
        [36.288425, 119.996796]
      ]).addTo(this.plotLayer);
    },
    // 进攻方向（尾）
    addTailedAttackArrow() {
      L.Plot.tailedAttackArrow([
        [36.138845, 120.039368],
        [36.141063, 120.064087],
        [36.260746, 120.050354]
      ]).addTo(this.plotLayer);
    },
    // 分队战斗行动
    addSquadCombat() {
      L.Plot.squadCombat([
        [36.141063, 120.102539],
        [36.248565, 120.102539],
        [36.370295, 120.261841]
      ]).addTo(this.plotLayer);
    },
    // 分队战斗行动（尾）
    addTailedSquadCombat() {
      L.Plot.tailedSquadCombat([
        [36.145569, 120.189056],
        [36.148341, 120.232315],
        [36.378035, 120.362091]
      ]).addTo(this.plotLayer);
    },
    // 钳击
    addDoubleArrow() {
      L.Plot.doubleArrow([
        [36.076713, 120.261841],
        [36.081153, 120.39093],
        [36.206468, 120.293427],
        [36.14439, 120.318146]
      ]).addTo(this.plotLayer);
    },

  }
};
</script>

<style scoped>
#map {
  width: 100%;
  height: calc(100vh);
  z-index: 1;
}
.draw {
  display: flex;
  z-index: 2;
  width: 100px;
  height: 50px;
  position: absolute;
  left: 50px;
  justify-content: center;
  align-items: center;
}

.disDraw {
  display: flex;
  z-index: 2;
  width: 100px;
  height: 50px;
  position: absolute;
  left: 200px;
  justify-content: center;
  align-items: center;
}
</style>
